一個類別繼承自另一個類別時,它會自動取得另一個類別的所有屬性和方法,同時還可以定義自己專屬的屬性和方法
python第一個要進行工作是把值分配給父類別的所有屬性,父類別一定要放在目前的程式檔案內,且放置位置要在子類別的前面,super()是特殊的函式會協助python把父類別和子類別連接起來
範例如下 :
# 父類別Car
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0
def get_name(self): # 印出名字
print(str(self.year) +" "+ self.brand)
def get_mile(self): # 存取公里數
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
def update_mile(self,mileage): # 更新公里數
self.miles = mileage
def add_mile(self,kilometer): # 增加公里數
self.miles += kilometer
def fill_gas(self): # 車子加油
print("This car need a gas tank")
# 子類別ElectriCar
class ElectricCar(Car): # 定義一個子類別,且括號內一定要放入父類別
def __init__(self,year,brand,color): # 接收Car實例所需要的資訊
super().__init__(year,brand,color) # 這行會使python呼叫ElectricCar父類別的__init__()方法,讓ElectricCar實例含有父類別的所有屬性
ecar1 = ElectricCar(2018,"toyota","black")
ecar1.get_name()
輸出結果 :
2018 toyota
當我們有一個從父類別繼承過來的子類別時,可以對以類別新增其專有的屬性和方法,這些都與父類別不同
範例如下 :
class Car():
---省略---
class ElectricCar(Car):
def __init__(self,year,brand,color):
super().__init__(year,brand,color)
self.battery_size = 100 # 新增一個屬性初始值為100
def get_battery(self): # 新增一個get_battery方法
print("Your "+self.brand+" has "+str(self.battery_size)+"-KWh battery")
ecar1 = ElectricCar(2018,"toyota","black")
ecar1.get_name()
ecar1.get_battery()
輸出結果 :
2018 toyota
Your toyota has 100-KWh battery
如果父類別的方法不符合子類別的需求,我們都可以覆寫,其作法是在子類別中定義一個與父類別方法有相同名稱的方法,這樣pythoon就不會去用父類別同名的方法,只會關注子類別中定義的這個方法
範例如下 :
class Car():
---省略---
class ElectricCar(Car):
def __init__(self,year,brand,color):
super().__init__(year,brand,color)
self.battery_size = 100
def get_battery(self):
print("Your "+self.brand+" has "+str(self.battery_size)+"-KWh battery")
def fill_gas(self): # 覆寫父類別的fill_gas方法
print("This car doesn't need a gas tank")
ecar1 = ElectricCar(2018,"toyota","black")
ecar1.get_name()
ecar1.get_battery()
ecar1.fill_gas()
輸出結果 :
2018 toyota
Your toyota has 100-KWh battery
This car doesn't need a gas tank
↓ car.py檔
class Car():
---省略---
class ElectricCar():
---省略---
↓ my_car.py檔
from car import Car # import陳述句會讓python開啟car模組並匯入Car類別
car1 = Car(2018,"toyota","black")
car1.get_name()
輸出結果 :
2018 toyota
↓ car.py檔
class Car():
---省略---
class ElectricCar():
---省略---
↓ my_car.py檔
from car import Car,ElectricCar # import陳述句會讓python開啟car模組並匯入Car和Electric類別
car1 = Car(2018,"toyota","black")
car1.get_name()
car1.update_mile(87)
car1.get_mile()
ecar1 = ElectricCar(2019,"benz","white")
ecar1.get_name()
ecar1.get_battery()
輸出結果 :
2018 toyota
Your toyota has 87 miles on it
2019 benz
Your benz has 100-KWh battery
↓ car.py檔
class Car():
---省略---
class ElectricCar():
---省略---
↓ my_car.py檔
import car # import整個car模組
car1 = car.Car(2018,"toyota","black") # 建立一個car1實例並用<模組名稱.類別名稱>語法來存取需要的類別
car1.get_name()
ecar1 = car.ElectricCar(2019,"benz","white")
ecar1.get_name()
輸出結果 :
2018 toyota
2019 benz
附上排版較精美的
HackMD網址:https://hackmd.io/E2_i7iuRSjSTtVMPLwBQ8w
資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯